//
//  MainViewController.swift
//  jackWu
//
//  Created by Lewhaming on 2016/11/18.
//  Copyright © 2016年 IQ. All rights reserved.
//

import UIKit


 class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
   
//        tabBar.tintColor = UIColor.orange
        
        
//        addChildViewControllers()
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.addSubview(composeButton)
        
        let rect = composeButton.frame.size
        //计算宽度
        let width = tabBar.bounds.width / CGFloat(childViewControllers.count)
        composeButton.frame = CGRect(x: 2*width, y: 0, width: width, height: rect.height)
    }
    
    
    
    
    
    //添加所有的子控制器
    func addChildViewControllers(){
        addChildViewController("HomeTableViewController", imageName: "tabbar_home", title: "首页")
        addChildViewController("MessageTableViewController", imageName: "tabbar_message_center", title: "消息")
        addChildViewController("NullTableViewController", imageName:"", title:"")

        addChildViewController("DiscoverTableViewController", imageName: "tabbar_discover", title: "发现")
        addChildViewController("ProfileTableViewController", imageName: "tabbar_profile", title: "我")
    }
    
    func addChildViewController(_ childController: String?, imageName: String?, title: String?) {
        
        IQLog(message: childController)
        //命名空间
        guard let name =  Bundle.main.infoDictionary!["CFBundleExecutable"] as? String  else {
            IQLog(message: "获取命名空间失败")
            return
        }
        
        var cls: AnyClass? = nil
        if  let vcName = childController{
            cls = NSClassFromString(name + "." + vcName)
        }
        
        guard let CTTypesetter = cls as? UITableViewController.Type else {
            IQLog(message: "cls 不能做UItableViewControl")
            return
        }
        
        let childController = CTTypesetter.init()
        
        childController.title = title
        if  let ivName = imageName{
            childController.tabBarItem.image = UIImage(named: ivName)
            childController.tabBarItem.selectedImage = UIImage(named: ivName + "_highlighted")
        }
        

        let nav = UINavigationController(rootViewController: childController)
        //4.将自控制器添加到view
        addChildViewController(nav)
    }
    
    @objc private func composeBtnClick(){
        IQLog(message: "msg")
        
    }
    
    // MARK: -- 懒加载 执行闭包
    lazy var composeButton:UIButton = {
        () ->UIButton
        in
        let btn = UIButton(imageName:"tabbar_compose_icon_add", backgroudImageName: "tabbar_compose_button")
        btn.addTarget(self, action:#selector(MainViewController.composeBtnClick), for: UIControlEvents.touchDown)
        
        return btn
    }()
    
    
   
}
